<template>
    <div class="goods-add-form">
        <div class="section1">
            <div class="pro_info_title" style="text-align: center;">
                <div
                    style="margin-left: 0px; height: 40px;width: 300px; text-align: center;line-height: 40px;float: left;font-weight: bold;">
                    {{ data.po_name }}&nbsp;{{ data.pb_code }}</div>
                <div
                    style="margin: 0 auto; height: 40px;width: 250px; text-align: center;line-height: 40px;float: right;">
                    <el-button plain @click="handleEdit">编辑</el-button>
                    <el-button plain @click="handleDelete">删除</el-button>
                    <el-button plain @click="handAudit">审核</el-button>
                </div>
            </div>
            <hr>

            <!-- 基本信息表格 -->
            <table style="width: 100%; border-collapse: collapse;border: none;">
                <tbody>
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">供应商</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ data.vendor_name }}
                        </td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">联系人</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ data.contacts_name }}</td>
                        <td style="padding: 10px 0px; color: #666;">联系电话</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.contacts_phone }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">关联采购订单</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.po_code }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">入库仓库</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ cwVaule(data.warehouse_code) }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">采购负责人</td>
                        <td style="padding: 10px 0px 10px 10px; min-width: 50px;">{{ userValue(data.po_rep_id) }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">入库状态</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ getStateText(data.pb_state) }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">操作人</td>
                        <td style="padding: 10px 0px 10px 10px; min-width: 50px;">{{ data.pb_operator || '无' }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">备注</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.remark || '无' }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">创建人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.create_by }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">创建时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ datetime(data.create_time) }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">修改人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.update_by ||'暂无修改'}}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">修改时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ datetime(data.update_time)||'暂无修改' }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">审核人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.pb_Audit_By||'未审核' }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">审核时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ datetime(data.pb_Audit_Time)||'未审核' }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">审核备注</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ data.pb_Audit_Remark||'无' }}</td>
                    </tr>
                </tbody>
            </table>
        </div>


        <div class="section2">
                    <el-table :data="detailsDatas" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
                        textAlign: 'center',
                        background: '#f5f7fa',
                        fontWeight: 'bold',
                        position: 'sticky',
                        top: 0
                    }">
                        <el-table-column prop="pro_code" label="产品编号" width="180" />
                        <el-table-column prop="pro_name" label="产品名称" />
                        <el-table-column prop="pro_brand" label="品牌" />
                        <el-table-column prop="pro_model" label="规格型号" />
                        <el-table-column prop="unitmeas_id" label="单位">
                            <template #default="scope">
                                <span>{{ measureValue(scope.row.unitmeas_id) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="po_number" label="采购数量" />
                        <el-table-column prop="details_monovalent" label="采购单价" />
                        <el-table-column prop="to_be_stored_qty" label="待入库数量" />
                        <el-table-column prop="details_storage" label="已入库数量" />
                        <el-table-column prop="details_storage" label="未入库数量">
                            <template #default="scope">
                                <span>{{  wrksjValue(scope.row) }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="height: 40px; line-height: 40px;">
                        <div style="display: inline-block; float: left;">合计</div>
                        <div style="display: inline-block; float:right">采购总数量：{{ sale_total_qty }} &nbsp;&nbsp;&nbsp;产品成本总额：{{
                                Number(sale_total_price).toFixed(2) }}
                        </div>
                    </div>
        </div>



        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="customer_handleClose">关闭</el-button>
        </div>
    </div>

    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
        <template #header>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                审核
            </div>
        </template>
        <hr>
        <div style="text-align: left;padding: 10px 0px;">
            <p>审核结果</p>
            <div class="my-2 ml-4">
                <el-radio-group v-model="auditStatus">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <p>审核意见</p>
                <el-input v-model="auditOpinion" style="width: 350px;height: 90px;"
                    :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入" />
            </div>
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="updateAudit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, markRaw,inject,watch } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { Delete } from '@element-plus/icons-vue'
import dayjs from 'dayjs';
import details from './Pbinfo_details.vue' // 需要调整这个组件以显示入库明细
import { useStore } from 'vuex';


export default {
    setup() {
        const store = useStore()
        const datas = store.state.PO_UpdeteArray

        const router = useRouter();
        const Router = useRouter();
        // const route = useRoute();
        // const datas = JSON.parse(String(route.query.rowData));

        const activeMenu = ref('details')// 默认显示入库明细

        const centerDialogVisible = ref(false);
        const auditStatus = ref('1');
        const auditOpinion = ref('');
        const measureOptios = ref([])//计量单位

        const userOptions = ref([])//数据源


        const cwdata = ref([])//仓库数据源

        
        // 入库状态文本转换

        const getStateText = (state) => {
            return state == 0 ? '未完成' : state == 2 ? '部分入库' : '全部入库';
        }

        const data = reactive({
            pb_code: '',       // 入库单编号

            po_name: '',       // 采购订单名称

            po_code: '',       // 采购订单编号

            vendor_name: '',   // 供应商名称

            contacts_name: '', // 联系人

            contacts_phone: '',// 联系电话

            warehouse_code: '',// 入库仓库

            pb_state: '',      // 入库状态

            pb_Inboundtime: '',// 入库时间

            pb_operator: '',   // 操作人

            create_by: '',     // 创建人

            create_time: '',   // 创建时间

            remark: '',        // 备注

            po_rep_id: '',      // 采购负责人ID

            update_by:'',

            update_time:'',

            pb_Audit:'',
            pb_Audit_By:'',
            pb_Audit_Time:'',
            pb_Audit_Remark:''
        });

        const menuComponentMap = {
            details: details, // 入库明细组件

            // audit: AuditRecord, // 审核记录组件（需要实现）

            // related: RelatedOrder // 关联采购订单组件（需要实现）

        };

        const currentComponent = ref(menuComponentMap.details);
        const detailsData = reactive([]); // 存储明细信息

        const detailsDatas = ref([])//存储明细信息2


        const PodetailsData = reactive([]); // 存储明细信息


        const sale_total_qty = ref(0)//记录销售数量

        const sale_total_price = ref(0)//记录采购金额

        const cost_total_proce = ref(0)//记录成本金额


        onMounted(() => {
            getUser();
            CK();//查询仓库

            info();
            infodata('details'); // 默认加载入库明细

            getMeasure();
            showPoDetails()
        });

        // 查询用户

        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                userOptions.value = result.data;
            }).catch(console.error);
        }

        // 将用户ID转换为用户名

        function userValue(userId) {
            if (!userId) return "无";
            const user = userOptions.value.find(u => u.user_id == userId);
            return user ? user.user_name : "无";
        }
        function CK(){
            axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect",{
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                cwdata.value = result.data
                // console.log(cwdata.value)

            }).catch((err) => {
                
            });
        }
        //将仓库数据转换对应的仓库

        function cwVaule(row) {
            if (!row) return "无";
            const parentUser = cwdata.value.find((user) => user.warehouse_code == row)
            return parentUser ? parentUser.warehouse_name : "无"
        }

        // 编辑功能

        function handleEdit() {
            if(datas.pb_Audit == 0||datas.pb_Audit == null){
                store.commit('PO_UpdeteArray', datas)
                router.push({
                path: '/main/pinv/PbUpdate',
                // query: { rowData: JSON.stringify(datas) }
            });
            }else{
                ElMessage.warning('该入库单已被审核，不可编辑！');
            }
        }

        // 审核功能

        function handAudit() {
            if (datas.pb_Audit == 0||datas.pb_Audit == null) {
                centerDialogVisible.value = true;
            } else {
                console.log(datas.pb_Audit)
                ElMessage.warning('该入库单已被审核，不可再次审核！');
                //  centerDialogVisible.value = true;

            }
        }
        // 更新审核状态

        function updateAudit() {
        try {
            // 1. 处理采购订单明细数据（添加空值检查和默认值）
            const details1 = PodetailsData.data?.map((item, index) => ({
            details_id: item?.details_id || 0,
            pro_Code: item.pro_code,
            Details_storage: (Number(item?.details_storage || 0) + Number(item?.to_be_stored_qty || 0)).toFixed(2)
            })) || [];

            // 2. 处理库存数据（完整验证和格式化）
            const details = detailsData.data?.map(item => {
            if (!item || !item.purwhsedetail_id) return null;
            
            return {
                purwhsedetail_id: item.purwhsedetail_id,
                Details_storage: (Number(item.details_storage || 0) + Number(item.to_be_stored_qty || 0)).toFixed(2),
                To_be_stored_qty: item.to_be_stored_qty || 0,
                
                // 库存数据
                pb_id: item.pb_id || datas.pb_id,
                stock_name: item.pro_name || '',
                pro_code: item.pro_code || '',
                pro_brand: item.pro_brand || '',
                dict_code: item.unitmeas_id || '',
                pro_attribbute_id: '1',
                stock_model: item.pro_model || '',
                pro_sale_price: '',
                pro_cost_price: item.details_monovalent || 0,
                stock_numder: (Number(item.details_storage || 0) + Number(item.to_be_stored_qty || 0)).toFixed(2),
                stock_entry_no: datas.pb_code || '',
                warehouse_code: datas.warehouse_code || '',
                zone_code: datas.zone_code || '',
                location_code: item.location_code || '',
                vendor_code: datas.vendor_code || '',
                vendor_name: datas.vendor_name || '',
                create_by: localStorage.getItem('userLName') || '',
                create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                del_flag: "0"
            };
            }).filter(Boolean) || []; // 过滤掉无效数据
            // 3. 构建请求数据
            const requestData = {
            pinv_Po: {
                po_Id: datas.po_id || 0
            },
            pinv_Details: details1.map((item,index) => ({
                details_id: item.details_id,
                details_storage: details[index]?.To_be_stored_qty || item.Details_storage,
                pro_code:item.pro_Code
            })),
            pinv_Pb: {
                po_Id: datas.po_id || 0,
                pb_id: datas.pb_id || 0,
                pb_Audit_By: localStorage.getItem('userLName') || '',
                pb_Audit_Time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                pb_Audit_Remark: auditOpinion.value || '',
                pb_Audit: auditStatus.value || '0'
            },
            pinv_Purwhsedetail: details.map(item => ({
                Purwhsedetail_id: item.purwhsedetail_id,
                details_storage: item.Details_storage,
                to_be_stored_qty: item.To_be_stored_qty,
                pb_id: item.pb_id,
                pb_code: datas.pb_code || '',
                pro_code: item.pro_code,
                Details_monovalent: item.pro_cost_price,
                warehouse_code: item.warehouse_code,
                zone_code: item.zone_code,
                location_code: item.location_code,
                vendor_code: item.vendor_code,
                vendor_name: item.vendor_name,
                create_by: item.create_by,
                create_time: item.create_time,
                del_flag: "0"
            }))
            };
            // console.log(details1)
            // console.log(requestData)
            // 4. 发送请求
            axios.put("http://localhost:5181/api/Pb/PutPodetails_Pb_PbdetailsUpdate", requestData, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
                }).then((result) => {
                if (!result.data) throw new Error('Empty response');
                
                switch (result.data.affectedRows) {
                    case 1:
                    ElMessage.success('审核成功！');
                    customer_handleClose();
                    break;
                    case 3:
                    ElMessage.error('当前仓库、库区、库位中不存在此商品，请确认仓库、库区、库位！');
                    break;
                    case 2:
                    ElMessage.error('产品不存在');
                    break;
                    case 10:
                    ElMessage.error('事务回滚，未知错误，调试查看');
                    break;
                    case 4:
                    ElMessage.error('未知错误');
                    break;
                    default:
                    ElMessage.error(`未知返回码: ${result.data.affectedRows}`);
                }
                    centerDialogVisible.value = false;
                }).catch((err) => {
                    console.error('API Error:', err);
                    ElMessage.error(`请求失败: ${err.message}`);
                });

            } catch (error) {
                console.error('Processing Error:', error);
                ElMessage.error(`数据处理失败: ${error.message}`);
            }
        }
        // 删除功能

        function handleDelete() {
            if(datas.pb_Audit == 0||datas.pb_Audit == null){
                ElMessageBox.confirm(
                    '此操作将删除该入库单信息，是否继续？',
                    '警告',
                    {
                        type: 'warning',
                        icon: markRaw(Delete),
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    }
                ).then(() => {
                    return axios.put('http://localhost:5181/api/Pb/PutPbDelete', {
                        pb_id: datas.pb_id,
                        del_flag: "1"
                    }, {
                        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                    });
                }).then((result) => {
                    if (result.data > 0) {
                        ElMessage.success("删除成功");
                        customer_handleClose();
                    } else {
                        ElMessage.error("删除失败");
                    }
                }).catch(() => {});
            }else{
                ElMessage.warning('订单已被审核，不可删除');
            }
        }
        const closeTab = inject('closeTab'); // 注入关闭方法

        // 关闭页面

        function customer_handleClose() {
            Router.push({
                    path: '/main/Pinv/Pb',
                });
                const targetPath = "/main/Pinv/Pb";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法

            }

            // 添加目标标签页（如果不存在）

            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "采购入库",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页

            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        // 日期格式化

        function datetime(isoTime) {
            if (!isoTime) return '';
            const date = new Date(isoTime);
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
        }


        // 加载数据

        function infodata(type) {
            if (type === 'details') {
                showDetails();
            }
            // 其他菜单项的数据加载可以在这里添加

        }

        // 显示入库明细

        async function showDetails() {
            try {
                const result = await axios.get("http://localhost:5181/api/Pb/Getpurwhsedetailwherecode", {
                    params: { code: data.pb_code },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });
                detailsData.data = result.data;
                detailsDatas.value = detailsData.data
            } catch (err) {
                console.error('加载明细失败', err);
                ElMessage.error('加载明细失败');
            }
        }

        async function showPoDetails() {
            try {
                const result = await axios.get("http://localhost:5181/api/Po/Getdetailswherecode", {
                    params: { code: datas.po_code },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });
                PodetailsData.data = result.data;
                // console.log(PodetailsData)

            } catch (err) {
                console.error('加载明细失败', err);
                ElMessage.error('加载明细失败');
            }
        }

        // 初始化数据

        function info() {
            data.pb_code = datas.pb_code;
            data.po_name = datas.po_name;
            data.po_code = datas.po_code;
            data.vendor_name = datas.vendor_name;
            data.contacts_name = datas.contacts_name;
            data.contacts_phone = datas.contacts_phone;
            data.warehouse_code = datas.warehouse_code;
            data.pb_state = datas.po_state; // 注意这里可能是pb_state

            data.pb_Inboundtime = datetime(datas.pb_Inboundtime);
            data.pb_operator = datas.pb_operator;
            data.create_by = datas.create_by;
            data.create_time = datetime(datas.create_time);
            data.remark = datas.remark;
            data.po_rep_id = datas.po_rep_id;
            data.pb_Audit_By = datas.pb_Audit_By;
            data.pb_Audit = datas.pb_Audit;
            data.pb_Audit_Time = datetime(datas.pb_Audit_Time);
            data.pb_Audit_Remark = datas.pb_Audit_Remark;
            data.update_by = datas.update_by;
            data.update_time = datetime(datas.update_time);
            console.log(data)
        }
        //查询计量单位

        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
                // console.log(measureOptios)

            }).catch((err) => {
                console.info(err)
            });
        }

        //根据计量单位id返回计量单位名称

        function measureValue(row) {
            if (!row) return "无";
            const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        watch( detailsDatas, (newVal) => {
            newVal.forEach(row => {
                // row.details_storage = Number((row.po_number || 0) * (row.details_monovalent || 0)).toFixed(2);

                row.pro_total_cost = Number((row.po_number || 0) * (row.pro_cost_price || 0)).toFixed(2);

                sale_total_qty.value += Number(row.po_number)/2
                cost_total_proce.value += Number(row.details_monovalent)
                sale_total_price.value = (Number(sale_total_qty.value) * Number(cost_total_proce.value).toFixed(2))/2;
                // num = Number(row.po_number) - Number(row.details_storage)

            });
        }, { deep: true })
        function wrksjValue(row){
            const wrksj = Number(row.po_number) - Number(row.details_storage)
            return Number(wrksj)
        }

        return {
            data,
            activeMenu,
            currentComponent,
            centerDialogVisible,
            auditStatus,
            auditOpinion,
            detailsData,
            detailsDatas,
            PodetailsData,
            measureOptios,
            sale_total_qty,
            sale_total_price,
            cost_total_proce,
            wrksjValue,
            getStateText,
            userValue,
            handleEdit,
            handleDelete,
            customer_handleClose,
            datetime,
            handAudit,
            updateAudit,
            cwVaule,
            measureValue,
            close: () => {
                centerDialogVisible.value = false;
                auditStatus.value = '1';
                auditOpinion.value = '';
            }
        };
    }
}
</script>

<style scoped>
.section2{
    margin-top: -20px;
}
.goods-add-form{
    margin-top: -40px;
}
/* 样式保持不变 */
.section {
    padding: 20px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-top: -20px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}

.section1 {
    padding: 20px;
    height: auto; /* 调整为自适应高度 */
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.pro_info_title {
    text-align: center;
    width: 100%;
    height: 40px;
}
</style>